<script setup lang="ts">
import { ref, getCurrentInstance, onMounted, watch, computed, onUnmounted } from 'vue'
import HoverDropdown from './common/HoverDropdown.vue';
import GuideCoin from './GuideCoin.vue';
import { useCoinStore } from '@/store/coin';
import { useThemeStore } from '@/store/theme';
import { userStore } from '@/store/user';
import { CoinItem } from "@/interfaces/currency.js";
import { formatNumberWithThousands } from '@/utils/utils';
const props = defineProps(['domInfo'])
const instance = getCurrentInstance()
const coinInfoDom = ref()
const isContentOverflowValue = ref(false)
const scrollLeft = ref(0)
const scrollWidth = ref(0)
const isHover = ref<boolean>(false)
const currencyId = ref<string>()
const isLoading = ref<boolean>(true)
const priceInfo = computed(() => {
    return useCoinStore().getPrice(useCoinStore().coinInfo.name)
})
let currencySocket: any
const coinInfo = ref<CoinItem>({
    src: '',
    percentText: '',
    currencyPair: '',
    amount: 0,
    externalPrice: 0,
    timestamp: 0,
    percent: 0,
    usdAmount: 0,
    cnyAmount: 0,
    hkdAmount: 0,
    eurAmount: 0,
    lowest: 0,
    highest: 0,
    open: 0,
    total: 0,
    checked: false,
    markPrice: 0
})

// const coinInfo = computed(() => {
//     isLoading.value = false
//     console.log(useCoinStore().spotKLine)
//     return useCoinStore().spotKLine[useCoinStore().coinInfo.name + '-USDT']
// })

const connectCurrency = () => {
    if (currencyId.value) {
        currencySocket.unsubscribe(currencyId.value, '/topic/market')
    }
    currencyId.value = Date.now().toString(36) + Math.floor(Math.random() * 1000).toString(36)

    currencySocket.subscribe(currencyId.value, `/topic/market`, (data: CoinItem) => {
        if (data.currencyPair === useCoinStore().coinInfo.name + '-USDT') {
            // coinInfo.value = data
            isLoading.value = false
            setTimeout(() => {
                if (scrollLeft.value) {
                    scrollFn('left')
                }
                isContentOverflow()
            }, 100);
        }
    })
}

const addLove = () => {
    if (userStore().loveList.includes(useCoinStore().coinInfo.name)) {
        userStore().remvoeLoveItem(useCoinStore().coinInfo.name)
    } else {
        userStore().addLoveItem(useCoinStore().coinInfo.name)
    }
}
const getSrc = () => {
    return useCoinStore().logoList ? 'https://file.uhx.io/' + (useCoinStore().logoList as Record<string, string>)[useCoinStore().coinInfo.name] : ''
}

const hoverFn = () => {
    isHover.value = true
}

const leaveFn = () => {
    isHover.value = false
}
const isContentOverflow = () => {
    if (!coinInfoDom.value) return false;
    const container = coinInfoDom.value;
    const containerWidth = container.clientWidth;
    const children = container.children as unknown as HTMLElement[];
    let totalChildrenWidth = 0;
    for (let i = 0; i < children.length; i++) {
        if (children[i].classList.contains('item')) {
            totalChildrenWidth += children[i].offsetWidth;
        }
    }
    totalChildrenWidth += 4 * 15.5;
    scrollWidth.value = totalChildrenWidth - containerWidth
    isContentOverflowValue.value = totalChildrenWidth > containerWidth;
};
const scrollFn = (type: string) => {
    const container = document.getElementById('aaa') as unknown as HTMLElement;
    scrollLeft.value = type === 'left' ? 99999 : 0
    container.scrollTo({
        left: scrollLeft.value,
        behavior: 'smooth'
    })
}
const emit = defineEmits(['showCoinInfo'])
const showCoinInfo = () => {
    emit('showCoinInfo')
}
watch(() => props.domInfo, (v) => {
    isContentOverflow()
})
watch(() => useCoinStore().spotKLine, (val) => {
    if (val) {
        isLoading.value = false
        coinInfo.value = val[useCoinStore().coinInfo.name + '-USDT'] || {
            src: '',
            percentText: '',
            currencyPair: '',
            amount: 0,
            externalPrice: 0,
            timestamp: 0,
            percent: 0,
            usdAmount: 0,
            cnyAmount: 0,
            hkdAmount: 0,
            eurAmount: 0,
            lowest: 0,
            highest: 0,
            open: 0,
            total: 0,
            checked: false,
            markPrice: 0
        }
    }
}, {
    deep: true
})
// watch(() => userStore().currencySocket, (val) => {
//     if (val) {
//         if (instance) {
//             currencySocket = instance.appContext.config.globalProperties.$currencySocket
//             if (currencySocket.connected) {
//                 connectCurrency()
//             }
//         }
//     }
// }, { immediate: true })
onMounted(() => {
})
onUnmounted(() => {
    if (currencySocket) {
        currencySocket.unsubscribe(currencyId.value, '/topic/market')
    }
})
watch(() => useCoinStore().coinInfo.name, () => {
    isLoading.value = true
})
</script>

<template>
    <div class="h-full px-[16px] flex items-center flex-nowrap" :class="[isLoading ? 'justify-center' : '']">
        <div v-show="!isLoading" class="hidden sm:flex items-center ">
            <div @click="addLove"
                class="w-[24px] mr-[4px] h-[24px] border-solid border-[1px] cursor-pointer border-[#ededed] dark:border-[#333b47] rounded-[6px] flex items-center justify-center">
                <span
                    :class="[userStore().loveList.includes(useCoinStore().coinInfo.name) ? 'icon-shoucang1 text-[#f0b90b]' : 'icon-shoucang text-[#bfbfbf] dark:text-[#4f5867]']"
                    class="iconfont text-[16px]"></span>
            </div>
            <img class="w-[24px] m-[4px]" :src="getSrc()" />
            <div class=" m-[4px] lg:block hidden">
                <div class="text-[20px] text-black font-bold dark:text-[#EAECEF]">{{ useCoinStore().coinInfo.name
                }}/USDT</div>
                <div class="text-[#9c9c9c] text-[12px] dark:text-[#707A8A]">UHX价格</div>
            </div>
            <HoverDropdown class="hidden md:block sm:block lg:hidden " @mouseenter="hoverFn" @mouseleave="leaveFn"
                :horizontal-offset-value="-78" :vertical-offset-value="5">
                <div class="m-[4px]">
                    <div class="text-[20px] text-black font-bold dark:text-[#EAECEF]">
                        <span>{{
                            useCoinStore().coinInfo.name
                        }}/USDT</span>
                        <span class="iconfont ml-[6px] text-[12px]"
                            :class="[isHover ? 'icon-xiangshang' : 'icon-xiangxia']"></span>
                    </div>
                    <div class="text-[#9c9c9c] text-[12px] dark:text-[#707A8A]">UHX价格</div>
                </div>
                <template #content>
                    <div class="w-[320px] box-border overflow-hidden ">
                        <!-- <GuideCoin /> -->
                    </div>
                </template>
            </HoverDropdown>
            <div class="ml-[10px] mr-[16px] relative">
                <div v-if="isContentOverflowValue && scrollLeft" @click="scrollFn('right')"
                    :style="{ background: useThemeStore().theme === 'light' ? `linear-gradient(270deg, #fff 0%, #fff calc(24px / 2), transparent 100%)` : `linear-gradient(270deg, #181a20 0%, #181a20 calc(24px / 2), transparent 100%)` }"
                    class=" absolute right-[-28px] cursor-pointer w-[12px] h-[38px] flex items-center z-[10]">
                    <span
                        class="iconfont icon-zuo font-bold  hover:text-[black] text-[#9C9C9C] text-[12px] dark:hover:text-[#EAECEF] dark:text-[#707A8A]"></span>
                </div>
                <div class="text-[20px] font-bold" :class="[coinInfo?.percent > 0 ? 'text-rise' : 'text-fall']">{{
                    priceInfo?.unitDecimals ? formatNumberWithThousands(coinInfo.amount.toFixed(priceInfo.unitDecimals))
                        :
                        formatNumberWithThousands(coinInfo?.amount) }}</div>
                <div class="text-[12px] text-black dark:text-[#EAECEF] ">${{
                    priceInfo?.unitDecimals ?
                        formatNumberWithThousands(coinInfo?.externalPrice.toFixed(priceInfo.unitDecimals))
                        :
                        formatNumberWithThousands(coinInfo?.externalPrice) }}
                </div>
            </div>
        </div>
        <div v-show="!isLoading" id="aaa" class="hidden overflow-hidden relative sm:flex">
            <div v-if="isContentOverflowValue && !scrollLeft" @click="scrollFn('left')"
                :style="{ background: useThemeStore().theme === 'light' ? `linear-gradient(270deg, #fff 0%, #fff calc(24px / 2), transparent 100%)` : `linear-gradient(270deg, #181a20 0%, #181a20 calc(24px / 2), transparent 100%)` }"
                class="absolute right-[0] z-[20] h-[100%] flex items-center w-[12px]  justify-center cursor-pointer">
                <span
                    class="iconfont icon-you text-[12px] font-bold hover:text-[black] text-[#9C9C9C] dark:hover:text-[#EAECEF] dark:text-[#707A8A]"></span>
            </div>
            <div class="flex flex-nowrap " ref="coinInfoDom">
                <div class="flex flex-col justify-between flex-shrink-0 item">
                    <div class="text-[12px] text-[#9c9c9c] dark:text-[#707A8A]">24h涨跌</div>
                    <div class="text-[12px] mt-[6px] " :class="[coinInfo?.percent > 0 ? 'text-rise' : 'text-fall']">
                        <!-- <span>726.25</span> -->
                        <span>{{ coinInfo?.percent > 0 ? '+' : '' }}{{ Number(coinInfo?.percent * 100).toFixed(2)
                        }}%</span>
                    </div>
                </div>
                <div class="ml-[16px] flex flex-col justify-between flex-shrink-0 item">
                    <div class="text-[12px] text-[#9c9c9c] dark:text-[#707A8A]">24h最高价</div>
                    <div class="text-[12px] mt-[6px] dark:text-[#EAECEF]">{{ priceInfo?.unitDecimals ?
                        formatNumberWithThousands(coinInfo?.highest.toFixed(
                            priceInfo?.unitDecimals)) : formatNumberWithThousands(coinInfo?.highest) }}</div>
                </div>
                <div class="ml-[16px] flex flex-col justify-between flex-shrink-0 item">
                    <div class="text-[12px] text-[#9c9c9c] dark:text-[#707A8A]">24h最低价</div>
                    <div class="text-[12px] mt-[6px] dark:text-[#EAECEF]">{{ priceInfo?.unitDecimals ?
                        formatNumberWithThousands(coinInfo?.lowest.toFixed(priceInfo?.unitDecimals)) :
                        formatNumberWithThousands(
                            coinInfo?.lowest) }}</div>
                </div>
                <div class="ml-[16px] flex flex-col justify-between flex-shrink-0 item">
                    <div class="text-[12px] text-[#9c9c9c] dark:text-[#707A8A]">24h成交量({{ useCoinStore().coinInfo.name
                        }})</div>
                    <div class="text-[12px] mt-[6px] dark:text-[#EAECEF]">{{ priceInfo?.coinDecimals ?
                        formatNumberWithThousands(coinInfo?.total.toFixed(priceInfo?.coinDecimals)) :
                        formatNumberWithThousands(coinInfo?.total) }}</div>
                </div>
                <div class="ml-[16px] flex flex-col justify-between flex-shrink-0 item">
                    <div class="text-[12px] text-[#9c9c9c] dark:text-[#707A8A]">24h成交量(USDT)</div>
                    <div class="text-[12px] mt-[6px] dark:text-[#EAECEF]">{{ priceInfo?.unitDecimals ?
                        formatNumberWithThousands(Number(coinInfo?.total *
                            coinInfo?.amount).toFixed(priceInfo?.unitDecimals)) :
                        formatNumberWithThousands(Number(coinInfo?.total *
                            coinInfo?.amount).toFixed(2)) }}</div>
                </div>
            </div>
        </div>
        <div v-show="!isLoading" class=" block sm:hidden py-[12px] h-[100%] box-border w-full">
            <div class="h-[32px] pb-[10px] flex items-center" @click="showCoinInfo">
                <div class="w-[24px] h-[24px] mr-[8px]">
                    <img :src="getSrc()" class="w-[100%] h-[100%]" />
                </div>
                <div class=" font-bold dark:text-[#EAECEF]">{{ useCoinStore().coinInfo.name
                }}/USDT</div>
                <span class="iconfont ml-[6px] text-[10px] dark:text-[#EAECEF]" :class="['icon-xiangxia']"></span>
            </div>
            <div class="flex h-[calc(100%-40px)] justify-between">
                <div class="flex justify-between flex-col">
                    <div>
                        <div class="text-[28px] font-bold "
                            :class="[coinInfo?.percent > 0 ? 'text-rise' : 'text-fall']">
                            {{
                                coinInfo?.amount }}</div>
                        <div class="text-[12px]">
                            <span class="dark:text-[#EAECEF]">${{ formatNumberWithThousands(coinInfo?.externalPrice)
                                }}</span>
                            <span class="ml-[8px]" :class="[coinInfo?.percent > 0 ? 'text-rise' : 'text-fall']"> {{
                                coinInfo?.percent >
                                    0 ? '+' : '' }}{{ Number(coinInfo?.percent *
                                    100).toFixed(2)
                                }}%</span>
                        </div>
                    </div>
                    <div @click="addLove"
                        class="w-[24px] mr-[4px] h-[24px] border-solid border-[1px] cursor-pointer border-[#ededed] dark:border-[#333b47] rounded-[6px] flex items-center justify-center">
                        <span
                            :class="[userStore().loveList.includes(useCoinStore().coinInfo.name) ? 'icon-shoucang1 text-[#f0b90b]' : 'icon-shoucang text-[#bfbfbf] dark:text-[#4f5867]']"
                            class="iconfont  text-[16px]"></span>
                    </div>
                </div>
                <div class="w-[180px] text-[12px] flex gap-[10px] flex-wrap">
                    <div class="w-[calc(40%-5px)] text-[10px] text-[#757575] dark:text-[#707A8A]">24h最高价</div>
                    <div class="w-[calc(60%-5px)] text-[10px] text-[#757575] dark:text-[#707A8A] ">24h成交量({{
                        useCoinStore().coinInfo.name
                        }})</div>
                    <div class="w-[calc(40%-5px)] dark:text-[#EAECEF] overflow-hidden text-ellipsis">{{
                        coinInfo?.highest
                    }}
                    </div>
                    <div class="w-[calc(60%-5px)] dark:text-[#EAECEF] overflow-hidden text-ellipsis">{{ coinInfo?.total
                    }}</div>
                    <div class="w-[calc(40%-5px)] text-[10px] text-[#757575] dark:text-[#707A8A]">24h最低价</div>
                    <div class="w-[calc(60%-5px)] text-[10px] text-[#757575] dark:text-[#707A8A]">24h成交量(USDT)</div>
                    <div class="w-[calc(40%-5px)] dark:text-[#EAECEF] overflow-hidden text-ellipsis">{{ coinInfo?.lowest
                        }}</div>
                    <div class="w-[calc(60%-5px)] dark:text-[#EAECEF] overflow-hidden text-ellipsis">{{
                        Number(coinInfo?.total *
                            coinInfo?.amount).toFixed(2) }}</div>
                </div>
            </div>
        </div>
        <Loading v-show="isLoading" />
    </div>
</template>

<style scoped></style>